package com.aaa.arouterone.utils

import android.app.Activity
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.Drawable
import android.os.Build
import android.os.StrictMode
import android.widget.ImageView
import com.aaa.arouterone.R
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.BitmapImageViewTarget
import com.bumptech.glide.signature.ObjectKey
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.InputStream
import java.net.URL
import java.net.URLConnection
import java.util.concurrent.ExecutionException


/**
 * detail: Glide 工具类
 *
 * @author Ttt
 * <pre>
 *
 *
 * init: GlideUtils.init(getApplicationContext());
 * use modify: 修改 defaultOptions() 配置、以及加载默认图片资源
 *
 *
 * Glide 详细使用
 * @see [](https://www.jianshu.com/p/7cfe2653a1fb)
 * Glide 文档
 *
 * @see [](https://muyangmin.github.io/glide-docs-cn)
 * 解决 Glide 加载图片闪烁的问题
 * @see [](https://blog.csdn.net/andcisco/article/details/96487800)
</pre> *
 */
object GlideUtils {
    /**
     * 1
     *
     * @param ctx
     * @param img
     * @param Type-100 高斯模糊  0  宽广告图   1 用户头像（圆形）   2 轮播图  3方形 4 购买vip 活动  5 邀请活动 大图   7  宝宝分享页面 缓存处理
     */
    @JvmOverloads
    fun ShowImgHead(
        ctx: Context?,
        img: ImageView?,
        img_url: String?,
        Type: Int = 1
    ) { //        if (TextUtils.isEmpty(img_url))
//            img_url = "error";
        if (ctx == null) {
            return
        }
        if (img == null) return
        var img_urls = img_url
//        img_urls = ""
        val options = getGlideOptions(Type)
        when (Type) {
//            -100 -> {
//                Glide.with(ctx!!).asBitmap().load(img_url).thumbnail(0.3f).apply(options)
//                    .bitmapTransform(BlurTransformation(context, radius))
//                    .into(img!!)
//            }
            -1 -> Glide.with(ctx!!).asBitmap().load(img_urls).thumbnail(0.3f).apply(options).into(
                object : BitmapImageViewTarget(img) {
                    override fun setResource(resource: Bitmap?) {
                        super.setResource(resource)
                        img?.setImageBitmap(resource)

                    }
                })
            0 -> Glide.with(ctx!!).asBitmap().load(img_urls).thumbnail(0.3f).apply(options)
                .into(img!!)
            1 -> Glide.with(ctx!!).asBitmap().load(img_urls).thumbnail(0.3f).apply(options)
                .into(img!!)

            2 ->  //             轮播图
                Glide.with(ctx!!).asBitmap().load(img_urls).thumbnail(0.3f).apply(options)
                    .into(img!!)
            4 ->  //             轮播图
            {
//                Glide.with(ctx!!).asBitmap().load(img_urls).thumbnail(0.3f).apply(options)
//                    .override(RxImageTool.dip2px(345f), RxImageTool.dip2px(55f)).fitCenter()
//                    .into(img!!)
            }
            5 ->  //
            {
//                Glide.with(ctx!!).asBitmap().load(img_urls).thumbnail(0.3f).apply(options)
//                    .override(RxImageTool.dip2px(375f), RxImageTool.dip2px(487f)).fitCenter()
//                    .into(img!!)
            }
            7 -> Glide.with(ctx!!).asBitmap().load(img_urls).thumbnail(0.3f).apply(options)
                .into(img!!)
            else -> {
                Glide.with(ctx!!).asBitmap().load(img_urls).thumbnail(0.3f).apply(options)
                    .into(img!!)
            }

        }
    }

    val glideOptions: RequestOptions
        get() = getGlideOptions(1)

    /**
     * @param type 类型 1  等待图片
     * @return
     */
    fun getGlideOptions(type: Int): RequestOptions {
        var drawableid = R.drawable.ic_launcher_background
        /* drawableid = when (type) {
             -1 -> R.drawable.logo_wait_v
             2 -> R.drawable.logo_wait
             1, 3 -> R.drawable.logo_wait_search
             5 -> R.drawable.ic_2929
             else -> R.drawable.logo_wait
         }*/

        return if (type == 7) {
            RequestOptions()
                .placeholder(drawableid)
                .error(drawableid)
                .centerCrop()
                .signature(ObjectKey(System.currentTimeMillis())) // 重点在这行;
        } else RequestOptions()
            .placeholder(drawableid)
            .error(drawableid)
            .centerCrop()
    }

    /**
     * 这是一个耗时的操作需要异步处理
     *
     * @param url 通过URL得到 Drawable
     * @return
     */
    fun getDrawableGlide(ctx: Context?, url: String?): Drawable? {
        try {
            return Glide.with(ctx!!)
                .load(url)
                .submit()
                .get()
        } catch (e: ExecutionException) {
            e.printStackTrace()
        } catch (e: InterruptedException) {
            e.printStackTrace()
        }
        return null
    }

    /**
     * 这是一个耗时的操作需要异步处理
     *
     * @param url 通过URL得到 Bitmap
     * @return
     */
    fun getBitmapGlide(ctx: Context?, url: String?): Bitmap? {
        try {
            return Glide.with(ctx!!)
                .asBitmap()
                .load(url)
                .submit()
                .get()
        } catch (e: ExecutionException) {
            e.printStackTrace()
        } catch (e: InterruptedException) {
            e.printStackTrace()
        }
        return null
    }

    /**
     * 图片url转bitmap
     */
    fun getBitMBitmap(urlpath: String?): Bitmap? {
        if (Build.VERSION.SDK_INT > 9) {
            val policy: StrictMode.ThreadPolicy =
                StrictMode.ThreadPolicy.Builder().permitAll().build()
            StrictMode.setThreadPolicy(policy)
        }
        var map: Bitmap? = null
        try {
            val url = URL(urlpath)
            val conn: URLConnection = url.openConnection()
            conn.connect()
            val `in`: InputStream
            `in` = conn.getInputStream()
            map = BitmapFactory.decodeStream(`in`)
            // TODO Auto-generated catch block
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return map
    }


    /**
     * 按质量压缩图片
     *
     * @param src         bitmap图片
     * @param maxByteSize 最大字节数
     * @param recycle
     * @return
     */
    fun compressByQuality(
        src: Bitmap?,
        maxByteSize: Long,
        recycle: Boolean
    ): ByteArray? {
        val baos = ByteArrayOutputStream()
        src?.compress(Bitmap.CompressFormat.JPEG, 100, baos)
        val bytes: ByteArray
        if (baos.size() <= maxByteSize) {
            bytes = baos.toByteArray()
        } else {
            baos.reset()
            src?.compress(Bitmap.CompressFormat.JPEG, 0, baos)
            if (baos.size() >= maxByteSize) {
                bytes = baos.toByteArray()
            } else { // find the best quality using binary search
                var st = 0
                var end = 100
                var mid = 0
                while (st < end) {
                    mid = (st + end) / 2
                    baos.reset()
                    src?.compress(Bitmap.CompressFormat.JPEG, mid, baos)
                    val len: Int = baos.size()
                    if (len.toLong() == maxByteSize) {
                        break
                    } else if (len > maxByteSize) {
                        end = mid - 1
                    } else {
                        st = mid + 1
                    }
                }
                if (end == mid - 1) {
                    baos.reset()
                    src?.compress(Bitmap.CompressFormat.JPEG, st, baos)
                }
                bytes = baos.toByteArray()
            }
        }
        if (recycle && !src!!.isRecycled) src?.recycle()
        return bytes
    }


}